// eslint-disable vue/custom-event-name-casing
import { bus } from '@web-utils/vue/mixin/bus'
import { patch, setNull } from '@/util'

export const patchTarget = {
  install(Vue) {
    Vue.prototype.$patch = patch
  }
}

export const setNullTarget = {
  install(Vue) {
    Vue.prototype.$setNull = setNull
  }
}

export const unset = {
  install(Vue) {
    Vue.prototype.$patch = patch
  }
}

export const validateId = {
  install(Vue) {
    function validateId(id) {
      return id && id > 0
    }

    Vue.prototype.$validateId = validateId

    Vue.prototype.$isNew = function (id) {
      return !validateId(id)
    }
  }
}

export const openTab = {
  install(Vue) {
    Vue.prototype.$openTab = function (path, tabTitle, query = {}, replace = false) {
      const route = { path, query: { tabTitle, ...query } }
      if (replace) {
        this.$router.replace(route)
      } else {
        this.$router.push(route)
      }
    }
  }
}

export const closeTab = {
  install(Vue) {
    Vue.prototype.$closeTab = function (path = '') {
      if (path) {
        bus.$emit('closeTab', path, this)
      } else {
        bus.$emit('closeTab', this.$route.path, this)
      }
    }
  }
}

export const reloadTableView = {
  install(Vue) {
    Vue.prototype.$reloadTableView = function (viewId, entity) {
      if (viewId) {
        bus.$emit('reloadTableView', viewId, entity)
      }
    }
  }
}

export const refreshTreeView = {
  install(Vue) {
    Vue.prototype.$reloadTreeView = function (viewId, entity) {
      if (viewId) {
        bus.$emit('reloadTreeView', viewId, entity)
      }
    }
  }
}

export const refreshHome = {
  install(Vue) {
    Vue.prototype.$refreshHome = function (viewId, entity) {
      if (viewId) {
        bus.$emit('refreshHome', viewId, entity)
      }
    }
  }
}

/**
 * 刷新待办事项页面
 * @type {{install(*): void}}
 */
export const refreshWork = {
  install(Vue) {
    Vue.prototype.$refreshWork = function (viewId = ['WorkToDo', 'WorkDone'], entity) {
      bus.$emit('reloadTableView', viewId, entity)
    }
  }
}
